package com.zaicheng.cloud.remotecall;/*
 @author zaicheng
 @version 1.0
 @date 2022-04-19
 @email zzc15847256473@163.com
 */

import com.zaicheng.cloud.Client;
//import com.zaicheng.cloud.demo.User;
import com.zaicheng.cloud.netty.RpcRequest;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class DefaultMethodHandler implements InvocationHandlerFactory.MethodHandler {

//    private final Client client;
//
//    private final Target<?> target;
//
//    private final RpcRequest.Options options;
//
//    public DefaultMethodHandler(Client client, Target<?> target, RpcRequest.Options options) {
//        this.client = client;
//        this.target = target;
//        this.options = options;
//    }

    private  final MethodHandle unboundHandle;

    private MethodHandle handle;

    public DefaultMethodHandler(Method defaultMethod) {
        try {
            Class<?> declaringClass = defaultMethod.getDeclaringClass();
            Field field = MethodHandles.Lookup.class.getDeclaredField("IMPL_LOOKUP");
            field.setAccessible(true);
            MethodHandles.Lookup lookup = (MethodHandles.Lookup)field.get((Object)null);
            this.unboundHandle = lookup.unreflectSpecial(defaultMethod, declaringClass);
        } catch (NoSuchFieldException var5) {
            throw new IllegalStateException(var5);
        } catch (IllegalAccessException var6) {
            throw new IllegalStateException(var6);
        }
    }

    public void bindTo(Object proxy) {
        if (this.handle != null) {
            throw new IllegalStateException("Attempted to rebind a default method handler that was already bound");
        } else {
            this.handle = this.unboundHandle.bindTo(proxy);
        }
    }

    /**
     *  args代表方法入参参数
     * @param args
     * @return
     */
    @Override
    public Object invoke(Target target,Method method,Object[] args) {

        for (Object object : args){
            System.out.println("动态代理获取方法参数："+args);
        }

//        User user = new User();

        return null;
    }
}
